<?php

namespace sffi\recovery\Driver;

use sffi\recovery\Core\DriverInterface;
use sffi\recovery\Core\TableEntity;

/**
 * 基础驱动
 */
abstract class BaseDriver implements DriverInterface
{
    /**、
     * 初始化数据库配置
     */
    public function __construct($config = [])
    {
        $this->setConfig($config);
    }

    /**
     * @var TableEntity[] $tables 多个数据表
     */
    protected array $tables = [];
    /**
     * @var array $config 数据库配置
     */
    protected array $config = [];
    /**
     * @var string $sql 数据库语句
     */
    protected string $sql;
    /**
     * @var bool $safeMode 安全模式（开启时，不许删除语句出现）
     */
    protected bool $safeMode=true;

    /**
     * 设置数据库配置
     */
    public function setConfig($config): self
    {
        $this->config = $config;
        $this->safeMode = $this->config['safe'] ?? true;
        return $this;
    }

    /**
     * 获取数据库配置
     */
    public function getConfig($config)
    {
        return $this->config;
    }

    /**
     * 设置表
     * @param TableEntity[] $tables
     */
    public function setTables(array $tables): self
    {
        $this->tables = $tables;
        return $this;
    }

    /**
     * 增加表实体
     * @param TableEntity $table 表实体
     */
    public function addTable(TableEntity $table): self
    {
        $this->tables[] = $table;
        return $this;
    }

    /**
     * 执行sql语句
     */
    public function exe(): bool
    {
        if (empty($this->config)) {
            throw new \Exception('缺少数据库配置项,请填写配置参数');
        }
        $mysql = mysqli_connect($this->config['hostname'], $this->config['username'], $this->config['password'], $this->config['database'], $this->config['hostport']);
        $res = mysqli_multi_query($mysql, $this->sql);
        mysqli_close($mysql);
        return $res;
    }

    /**
     * 生成sql
     */
    public function generalSql(): string
    {
        $sql = '';
        foreach ($this->tables as $table) {
            $sql .= $table->generalSql();
        }
        return $sql;
    }

    /**
     * 获取sql
     * @return string
     */
    public function getSql(): string
    {
        return $this->sql;
    }
    
    /**
     * 检查mysql中是否含有删除语句
     * @var string $content
     */
    public function checkMysqlIncludeDelete(string $content)
    {
        $size = preg_match('/\s?(delete|TRUNCATE|update|DROP)\s/i', $content);
        if ($size > 0 && $this->safeMode) {
            throw new \Exception('不能包含删除或更新语句');
        }
    }
}